package com.ssu.judea.travlog;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import org.json.JSONException;
import org.json.JSONObject;

import com.ssu.judea.travlog.util.HttpFileUploadHelper;
import com.ssu.judea.travlog.util.HttpHelper;
import com.ssu.judea.travlog.util.JSONParseHelper;
import com.ssu.judea.travlog.util.TravlogNameValuePair;
import com.ssu.judea.travlog.vo.Member;

import android.app.Application;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class TravlogApplication extends Application {
	
	private ProgressDialog progressDialog;
	private LocationManager locationManager;
	private Location currentLocation;
	private DisplayLocationListener listener;

	private Geocoder geocoder;
	
	public boolean isAllowedUser = false;
	public Member currentUser;

	//private String SERVER_URL = "//changdoc.homeip.net/TravlogServer";
	private String SERVER_URL = "//travlog.wo.tc";
	private String REQUEST_SERVLET = "/auth.m";

	private String ACTION_CHECK_AUTH = "checkAuth";
	private String ACTION_TO_AUTH_PAGE = "auth";
	private String ACTION_GET_CURRENT_SESSION = "getCurrentSession";
	private String ACTION_LOGOUT = "logout";
	private String ACTION_IMAGE_UPLOAD = "imageUpload";
	private String ACTION_WRITE_POST = "writePost";
	
	private String ACTION_GET_USER_POST_DATE_LIST = "getUserPostDateList";
	private String ACTION_GET_USER_POST_BY_DATE = "getUserPostByDate";
	private String ACTION_GET_RECENT_OPEN_POSTS = "getRecentOpenPosts";
	private String ACTION_GET_FOLLOWERS_LIST = "getFollowersPosts";
	
	private String ACTION_DO_FOLLOW = "follow";
	private String ACTION_DO_MENTION = "mention";
	
	private int INDEX_ACTION = 0;
	private int INDEX_PARAMS = 1;
	private int INDEX_HTTP_METHOD = 2;
	private int INDEX_END_MSG = 3;

	private String DEFAULT_END_MSG = "default";

	private String METHOD_POST = "post";
	//private String METHOD_GET = "get";

	public static String PARAMS_ACTION = "action";

	private HttpHelper http;
	


	public TravlogApplication() {
		http = new HttpHelper();
	}
	
	@Override
	public void onTerminate() {
		super.onTerminate();
		
		locationManager.removeUpdates(listener);
	}
	
	public DisplayLocationListener getDisplayLocationListener(Context context){
		geocoder = new Geocoder(context, Locale.getDefault());
		return listener = new DisplayLocationListener();
	}
	
	private class DisplayLocationListener implements LocationListener {

		public void onLocationChanged(Location location) {
                currentLocation = location;
                try {
					List<Address> addressList = geocoder.getFromLocation(currentLocation.getLatitude(), currentLocation.getLongitude(), 1);
					
					for(int i = 0; i<addressList.size();i++){
						Address curAddress  = addressList.get(i);
						Log.v("changdoc",currentLocation.getLatitude()+"/"+currentLocation.getLongitude()+curAddress.getCountryName());
						for(int j = 0; j<=curAddress.getMaxAddressLineIndex();j++){
							Log.v("changdoc",curAddress.getAddressLine(j));
						}
						
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
        }

        public void onProviderDisabled(String provider) {        }

        public void onProviderEnabled(String provider) {        }

        public void onStatusChanged(String provider, int status, Bundle extras) {        }
	}

	public void alert(String msg) {
		Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
	}
	
	public void alert(String msg, boolean isLong) {
		Toast.makeText(this, msg, isLong?Toast.LENGTH_LONG:Toast.LENGTH_SHORT).show();
	}

	public void checkAuth(TravlogActivity requestActivity) {
		// ���� �������� ���ø����̼��� ���� ������ ���� �� ȸ�������� �����ϴ��� ������
		// �����Ѵٸ� seq,profileUrl,TwitterID�θ� ������ Member��ü ���� ����
		JSONObject jsonAction = JSONParseHelper.getActionJSONObject(ACTION_CHECK_AUTH);

		currentAcitivity = requestActivity;
		backgroundJob = new BackgroundJob();
		currentMsg = "Checking user info...";
		backgroundJob.execute(jsonAction.toString(), "", METHOD_POST, DEFAULT_END_MSG);
	}

	public void getCurrentSession(TravlogActivity requestActivity) {
		//���� �������� ���ø����̼��� ������ ���ǰ��� �����´�.
		JSONObject jsonAction = JSONParseHelper.getActionJSONObject(ACTION_GET_CURRENT_SESSION);

		currentAcitivity = requestActivity;
		backgroundJob = new BackgroundJob();

		backgroundJob.execute(jsonAction.toString(), "", METHOD_POST, DEFAULT_END_MSG);
	}

	public String getAuthPageUrl(TravlogActivity requestActivity, String sessionId) {
		//���� ���� ������ session���̵� �����ϸ鼭 Twitter ���� �������� redirect�ɼ��ְ� URL����
		return "http:"+getSERVER_URL() + REQUEST_SERVLET + "?" + PARAMS_ACTION + "="+ ACTION_TO_AUTH_PAGE + "&session="+sessionId;
	}
	
	public void doLogout(TravlogActivity requestActivity) {
		JSONObject jsonAction = JSONParseHelper.getActionJSONObject(ACTION_LOGOUT);
		currentUser = new Member();
		isAllowedUser = false;
		
		currentAcitivity = requestActivity;
		backgroundJob = new BackgroundJob();
		currentMsg = "Trying logout...";
		backgroundJob.execute(jsonAction.toString(), "", METHOD_POST, "Logout done.");
	}

	
	public void doFileUpload(TravlogActivity requestActivity, String fileString){
		JSONObject jsonAction = JSONParseHelper.getActionJSONObject(ACTION_IMAGE_UPLOAD);
		
		currentAcitivity = requestActivity;
		backgroundJob = new BackgroundJob();
		currentMsg = "Image Uploading...";
		backgroundJob.execute(jsonAction.toString(),fileString, METHOD_POST,"Image Upload Done.");
	}
	
	public void doWritePost(TravlogActivity requestActivity, String imgUrl, String content, String open, String share, Location postingLocation) {
		JSONObject jsonAction = JSONParseHelper.getActionJSONObject(ACTION_WRITE_POST);
		
		JSONObject jsonParams = new JSONObject();
		try{
			if(postingLocation!=null){
				if(imgUrl.length()>0)jsonParams.put("image", imgUrl);
				if(content.length()>0)jsonParams.put("content", content);
				jsonParams.put("open", open);
				jsonParams.put("share", share);
				jsonParams.put("lat", postingLocation.getLatitude());
				jsonParams.put("lot", postingLocation.getLongitude());
				jsonParams.put("seq", currentUser.getMemberseq());
			}
		}catch(JSONException e){
			Log.e("changdoc",e.getMessage());
		}
		
		currentAcitivity = requestActivity;
		backgroundJob = new BackgroundJob();
		currentMsg = "Post Writing...";
		backgroundJob.execute(jsonAction.toString(),jsonParams.toString(), METHOD_POST,"Post Write Done.");
	}
	
	public void getUserPostDateList(TravlogActivity requestActivity, int memberseq) {
		JSONObject jsonAction = JSONParseHelper.getActionJSONObject(ACTION_GET_USER_POST_DATE_LIST);
		
		JSONObject jsonParams = new JSONObject();
		try{
			jsonParams.put("seq", memberseq);
		}catch(JSONException e){
			Log.e("changdoc",e.getMessage());
		}
		
		currentAcitivity = requestActivity;
		backgroundJob = new BackgroundJob();
		currentMsg = "Loading Postings...";
		backgroundJob.execute(jsonAction.toString(),jsonParams.toString(), METHOD_POST,"Loading Postings Done.");
	}
	
	public void getFollowersList(TravlogActivity requestActivity, int memberseq){
		JSONObject jsonAction = JSONParseHelper.getActionJSONObject(ACTION_GET_FOLLOWERS_LIST);
		
		JSONObject jsonParams = new JSONObject();
		try{
			jsonParams.put("seq", memberseq);
		}catch(JSONException e){
			Log.e("changdoc",e.getMessage());
		}
		
		currentAcitivity = requestActivity;
		backgroundJob = new BackgroundJob();
		currentMsg = "Loading Followers Postings...";
		backgroundJob.execute(jsonAction.toString(),jsonParams.toString(), METHOD_POST,"Loading Followers Postings Done.");
	}
	
	public void getUserPostByDate(TravlogActivity requestActivity,int memberseq, String date) {
		JSONObject jsonAction = JSONParseHelper.getActionJSONObject(ACTION_GET_USER_POST_BY_DATE);
		
		JSONObject jsonParams = new JSONObject();
		try{
			jsonParams.put("seq", memberseq);
			jsonParams.put("date", date);
		}catch(JSONException e){
			Log.e("changdoc",e.getMessage());
		}
		
		currentAcitivity = requestActivity;
		backgroundJob = new BackgroundJob();
		currentMsg = "Loading Postings...";
		backgroundJob.execute(jsonAction.toString(),jsonParams.toString(), METHOD_POST,"Loading Postings Done.");
	}
	
	public void getRecentOpenPosts(TravlogActivity requestActivity){
		JSONObject jsonAction = JSONParseHelper.getActionJSONObject(ACTION_GET_RECENT_OPEN_POSTS);
		
		currentAcitivity = requestActivity;
		backgroundJob = new BackgroundJob();
		currentMsg = "Loading Postings...";
		backgroundJob.execute(jsonAction.toString(),"", METHOD_POST,"Loading Postings Done.");
	}
	
	public void doFollow(ViewDetailActivity requestActivity, String targetMemberId) {
		JSONObject jsonAction = JSONParseHelper.getActionJSONObject(ACTION_DO_FOLLOW);
		
		JSONObject jsonParams = new JSONObject();
		try{
			jsonParams.put("seq",currentUser.getMemberseq());
			jsonParams.put("target", targetMemberId);
		}catch(JSONException e){
			Log.e("changdoc",e.getMessage());
		}
		
		currentAcitivity = requestActivity;
		backgroundJob = new BackgroundJob();
		currentMsg = "Following @"+targetMemberId+"...";
		backgroundJob.execute(jsonAction.toString(),jsonParams.toString(), METHOD_POST,"Process is Done.");
	}
	
	public void doWriteMention(UserMentionActivity requestActivity, String content) {
		JSONObject jsonAction = JSONParseHelper.getActionJSONObject(ACTION_DO_MENTION);
		
		JSONObject jsonParams = new JSONObject();
		try{
			jsonParams.put("seq",currentUser.getMemberseq());
			jsonParams.put("text", content);
		}catch(JSONException e){
			Log.e("changdoc",e.getMessage());
		}
		
		currentAcitivity = requestActivity;
		backgroundJob = new BackgroundJob();
		currentMsg = "Writing mentions...";
		backgroundJob.execute(jsonAction.toString(),jsonParams.toString(), METHOD_POST,"Write mentions Done.");
	}


	public void setLocationManager(LocationManager locationManager) {
		this.locationManager = locationManager;
	}

	public LocationManager getLocationManager() {
		return locationManager;
	}

	public String getSERVER_URL() {
		return SERVER_URL;
	}


	private TravlogActivity currentAcitivity;
	private BackgroundJob backgroundJob;
	private String currentMsg = "Loading please wait..";
	/*
	 * Async Start
	 */
	private class BackgroundJob extends AsyncTask<String, Integer, String>
			implements OnCancelListener {
		
		private String defaultMsg = "Loading done..\nThe results being generated...";
		private String currentEndMsg = defaultMsg;
		private String currentAction = "";

		@Override
		protected void onPreExecute() {
			progressDialog = ProgressDialog.show((Context) currentAcitivity,
					"", currentMsg, true, true, this);
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			// progressDialog.setMessage("Loading Please wait..\n" + values[0]
			// + "% Completed");
		}

		@Override
		protected void onPostExecute(String result) {
			// Async Work done.
			super.onPostExecute(result);
			progressDialog.setMessage(currentEndMsg);
			
			progressDialog.cancel();
			if (result != null && result.length() > 0) {
				doTravlogComplete(result);
			} else {
				alert("Not Exist Result");
			}
			
			
			
			currentAction = "";
			
		}

		private void doTravlogComplete(String result) {
			Log.e("changdoc", "BACKGROUND DONE!!"+result);
			
			if(result.equals("error")){
				alert("Something worng!");
				return ;
			}
			try {
				/*
				 * 
				 */
				if (currentAction.equals(ACTION_CHECK_AUTH)) {
					currentUser =JSONParseHelper.parseToMember(new JSONObject(result));
					if(currentUser!=null)isAllowedUser = true;
					else isAllowedUser = false;
					
					((ConfigureActivity) currentAcitivity)
							.completeAuthentication(currentUser);
				} else if (currentAction.equals(ACTION_GET_CURRENT_SESSION)) {
					((ConfigureActivity) currentAcitivity)
							.completeGetCurrentSession(result.trim());
				} else if (currentAction.equals(ACTION_IMAGE_UPLOAD)){
					((WriteActivity) currentAcitivity)
					.completeImageUpload(result.trim());
				} else if (currentAction.equals(ACTION_WRITE_POST)){
					((WriteActivity) currentAcitivity)
					.completeWritePost(result.trim());
				} else if (currentAction.equals(ACTION_LOGOUT)){
					((MainActivity) currentAcitivity)
					.completeLogout(result.trim());
				} else if (currentAction.equals(ACTION_GET_USER_POST_DATE_LIST) || currentAction.equals(ACTION_GET_FOLLOWERS_LIST) ){
					((ViewListActivity) currentAcitivity)
					.completeGetUserPostDateList(result.trim());
				} else if (currentAction.equals(ACTION_GET_USER_POST_BY_DATE)){
					((ViewDetailActivity) currentAcitivity)
					.completeGetUserPostByDate(result.trim());
				} else if (currentAction.equals(ACTION_GET_RECENT_OPEN_POSTS)){
					((ViewRecentActivity)currentAcitivity).completeRecentOpenPosts(result.trim());
				} else if (currentAction.equals(ACTION_DO_FOLLOW)){
					((ViewDetailActivity)currentAcitivity).completeFollow(result.trim());
				} else if (currentAction.equals(ACTION_DO_MENTION)){
					((UserMentionActivity)currentAcitivity).completeWriteMention(result.trim());
				}
			} catch (JSONException e) {
			}
		}

		@Override
		protected String doInBackground(String... params) {
			ArrayList<String> st = new ArrayList<String>();
			for(int i = 0;i<params.length;i++)
				st.add(params[i]);
			
			if (params.length == 4) {
				
				if (!params[INDEX_END_MSG].equals(DEFAULT_END_MSG)) {
					currentEndMsg = params[INDEX_END_MSG];
				}else{
					currentEndMsg = defaultMsg;
				}
				
				
				
				ArrayList<TravlogNameValuePair> paramList = new ArrayList<TravlogNameValuePair>();
				

				try {
					if(params[INDEX_ACTION]!=null && params[INDEX_ACTION].length()>0){
						// Action parameter setting
						JSONObject jsonAction = new JSONObject(params[INDEX_ACTION]);
						TravlogNameValuePair nvp = new TravlogNameValuePair(PARAMS_ACTION,jsonAction
								.getString(PARAMS_ACTION));
						paramList.add(nvp);
					
						//Current Action set
						currentAction = jsonAction.getString(PARAMS_ACTION);
					}
					
					
					if(params[INDEX_PARAMS]!=null && params[INDEX_PARAMS].length()>0 && params[INDEX_PARAMS].lastIndexOf("}")>0){
						// Extra Parameter setting
						JSONObject jsonParams = new JSONObject(params[INDEX_PARAMS]);
						
						
						Iterator<?> keys = jsonParams.keys();
						while (keys.hasNext()) {
							String currentKey = String.valueOf(keys.next());
							TravlogNameValuePair nvp = new TravlogNameValuePair(currentKey,  jsonParams.getString(currentKey));
							paramList.add(nvp);
							Log.v("changdoc",currentAction+"current Params:"+currentKey+":"+jsonParams.getString(currentKey));
						}
					}
				} catch (JSONException e) {
					Log.e("changdoc", "doInBackground : "+e.getMessage());
					return "";
				}
				
				
				if(currentAction.equals(ACTION_IMAGE_UPLOAD)){
					HttpFileUploadHelper fileUploader = new HttpFileUploadHelper();
					return fileUploader.HttpFileUpload(getSERVER_URL() + REQUEST_SERVLET + "?action="+ACTION_IMAGE_UPLOAD, params[INDEX_PARAMS]);
				}else{
					if (http == null)
						http = new HttpHelper();
					return http.getResultFromUrl(getSERVER_URL() + REQUEST_SERVLET,
							paramList, params[INDEX_HTTP_METHOD].equals(METHOD_POST) ? true : false);
				}

			} else {
				// background params policy illegal
				return "";
			}
		}

		@Override
		public void onCancel(DialogInterface dialog) {
			// onCancel
			Log.e("changdoc","onCancel");
		}
	}
	/*
	 * Async END
	 */

	

	
	

}
